[TOC]

User-defined Function

You can write your own functions to make your code modular and reusable. Suppose you are working on a project where you need to calculate the distance between two points, namely, and . This can be done by the following code snippet:

% Calculating distance of p1 and p2.

p1 = [x1, y1]
p2 = [x2, y2]
d = sqrt((p1(1) - p2(1))^2 + (p1(2) - p2(2))^2)

The above code is fine. However, if you need to compute the distance repeatedly, it becomes inconvenient and error prone. To adopt a good programming style, you should define a function named, say, distance, which is called wherever you need to calculate a distance. To define the function, you create a new .m file named distance.m and put the following code in the file:

function d = distance(p1, p2)

d = sqrt((p1(1) - p2(1))^2 + (p1(2) - p2(2))^2)

end

When you need to compute a distance, you simply call:

d = distance(p1, p2)

The code above is more modular. If you later use another mathematical expression for the distance, you only need to modify distance.m instead of making changes in multiple places of the project.

Defining a Function

To define a function, you need to create an .m file:

  1. The file should have the same name as the function. (For example, if the function is named distance, the file should be named distance.m.)
  2. If you are running from the console when the function is called, the file should be put in the work folder. When a function is called, the app searches in the work folder for a .m file with the same name. If such a file cannot be found in the work folder, a file-not-found error is thrown.
  3. If you are running a script from the editor (by tapping the editor's run button) when the function is called, the work folder will be temporarily switched to the folder that contains the script. In this case, the file defining the function should be placed in the same folder as the script.
  4. A built-in function has a higher precedence. If your function has a name equal to a built-in function’s name, the latter is called. More details can be found in the document page "Precedence".

A function definition has the following syntax:

function [out_1, ..., out_n] = fun(in_1, ..., in_m)

statement_1
statement_2
...
statment_k

end

function & end Keywords

  1. A function starts with the keyword function and ends with the keyword end.
  2. If end is omitted, it is assumed that the whole file contains just one function.
  3. You must not add any contents before keyword function, except whitespaces, newlines, and comments. Otherwise, the function is considered as a local function.

Function Body

  1. The function body is enclosed by the keywords function and end.
  2. It is consisted of a list of statements.
  3. An empty body (no statement) is allowed.

Output Arguments

  1. out_1, ..., out_n are output arguments.
  2. An output argument must have been assigned a value inside the function. Otherwise, a variable-not-found error will be thrown when the function attempts to return values to the caller.
  3. If it has just one output argument, you can remove the square brackets and use out = fun(in_1, ..., in_m) instead.
  4. If there is no argument, you can use either fun(in_1, ..., in_m) or [] = fun(in_1, ..., in_m).

Input Arguments

  1. in_1, ..., in_m are the input arguments.

  2. If it has no input arguments, you can use either one of these:

Calling a Function

To call a function, you need to make sure that the .m file defining the function is in the work directory. To facilitate our discussion, we consider a function with the following declaration:

function [out1, out2, out3] = fun(in1, in2)
%
% Some statements
%
end
  1. You call this function by calling fun(in1, in2).

  2. If the function definition has output arguments, you should provide no more than outputs when you call the function. If you provide outputs, where , the first outputs will be returned. Therefore, function calls in the following are valid:

Variable Scope

Each function has its own workspace. Variables defined in other workspaces are not accessible from within the function body. Similarly, variables defined in a function body are not accessible from the outside of the function. Once the execution of a function has finished, all variables in the function's workspace are cleared immediately.

Function Handle

A function handle is created using the @ operator. A function handle is stored in a workspace as a variable, and can be passed to another function as an input argument.

Suppose that we define the following function, which computes the absolute value of an input array:

function out1 = my_abs(in1)

out1 = abs(in1);

end

Then, we create the function handle fh of the function my_abs:

Input
fh = @my_abs
Output
fh = (main function)
 @my_abs

Then, we can call a1 = fh(-2) to get the absolute value of -2:

a1 = 
 2.0000

A function handle can be passed to another function as an input argument. For example, we create the anonymous function apply = @(operation, array) operation(array), which applies a given operation to an array. In the following, r is a matrix with some negative values. Then, we apply a given operation (finding absolute value) to r.

Input
apply = @(operation, array) operation(array)
% Random array with some negative values.
r = rand(3) - 0.5;
% Function handle of my_abs
fh = @my_abs
% Compute the absolute values of elements in r.
x = apply(fh, r)
Output
apply = (anonymous function)
 @(operation, array)operation(array)

fh = (main function)
 @my_abs

x = 1e-1 × 
 0.4921   0.6313   1.0245
 1.0711   4.7865   1.7607
 3.2648   1.8482   4.9839